package com.pethospital.service.impl;

import com.pethospital.dao.UserDao;
import com.pethospital.dao.impl.UserDaoImpl;
import com.pethospital.entity.PageResult;
import com.pethospital.entity.User;
import com.pethospital.service.UserService;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 用户服务实现类
 * User Service Implementation
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class UserServiceImpl implements UserService {
    
    private UserDao userDao = new UserDaoImpl();
    
    @Override
    public User login(String username, String password) {
        if (username == null || username.trim().isEmpty() || 
            password == null || password.trim().isEmpty()) {
            return null;
        }
        
        return userDao.findByUsernameAndPassword(username.trim(), password);
    }
    
    @Override
    public boolean register(User user) {
        // 验证用户数据
        String validationResult = validateUser(user, false);
        if (validationResult != null) {
            return false;
        }
        
        // 检查用户名是否已存在
        if (userDao.existsByUsername(user.getUsername())) {
            return false;
        }
        
        // 检查邮箱是否已存在
        if (user.getEmail() != null && !user.getEmail().trim().isEmpty() && 
            userDao.existsByEmail(user.getEmail())) {
            return false;
        }
        
        // 设置默认值
        if (user.getUserType() == null || user.getUserType().trim().isEmpty()) {
            user.setUserType("user");
        }
        if (user.getStatus() == null || user.getStatus().trim().isEmpty()) {
            user.setStatus("active");
        }
        
        return userDao.insert(user) > 0;
    }
    
    @Override
    public User getUserById(Integer userId) {
        if (userId == null || userId <= 0) {
            return null;
        }
        return userDao.findById(userId);
    }
    
    @Override
    public User getUserByUsername(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        return userDao.findByUsername(username.trim());
    }
    
    @Override
    public boolean updateUser(User user) {
        if (user == null || user.getUserId() == null) {
            return false;
        }
        
        // 验证用户数据
        String validationResult = validateUser(user, true);
        if (validationResult != null) {
            return false;
        }
        
        // 检查邮箱是否被其他用户使用
        if (user.getEmail() != null && !user.getEmail().trim().isEmpty()) {
            User existingUser = userDao.findByUsername(user.getUsername());
            if (existingUser != null && !existingUser.getUserId().equals(user.getUserId()) &&
                user.getEmail().equals(existingUser.getEmail())) {
                return false;
            }
        }
        
        return userDao.update(user) > 0;
    }
    
    @Override
    public boolean deleteUser(Integer userId) {
        if (userId == null || userId <= 0) {
            return false;
        }
        
        // 不能删除管理员账户
        User user = userDao.findById(userId);
        if (user != null && "admin".equals(user.getUserType())) {
            return false;
        }
        
        return userDao.delete(userId) > 0;
    }
    
    @Override
    public boolean batchDeleteUsers(Integer[] userIds) {
        if (userIds == null || userIds.length == 0) {
            return false;
        }
        
        // 过滤掉管理员账户
        List<Integer> validIds = new java.util.ArrayList<>();
        for (Integer userId : userIds) {
            User user = userDao.findById(userId);
            if (user != null && !"admin".equals(user.getUserType())) {
                validIds.add(userId);
            }
        }
        
        if (validIds.isEmpty()) {
            return false;
        }
        
        return userDao.batchDelete(validIds.toArray(new Integer[0])) > 0;
    }
    
    @Override
    public List<User> getAllUsers() {
        return userDao.findAll();
    }
    
    @Override
    public PageResult<User> getUsersByPage(int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;
        
        return userDao.findByPage(currentPage, pageSize);
    }
    
    @Override
    public PageResult<User> searchUsers(String username, String realName, String userType,
                                      String status, int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;

        return userDao.findByCondition(username, realName, userType, status, currentPage, pageSize);
    }

    @Override
    public PageResult<User> searchUsers(String username, String realName, String userType,
                                      String status, String sortField, String sortOrder,
                                      int currentPage, int pageSize) {
        if (currentPage <= 0) currentPage = 1;
        if (pageSize <= 0) pageSize = 10;

        return userDao.findByConditionWithSort(username, realName, userType, status,
                                             sortField, sortOrder, currentPage, pageSize);
    }
    
    @Override
    public long getTotalUserCount() {
        return userDao.countAll();
    }
    
    @Override
    public long getUserCountByType(String userType) {
        if (userType == null || userType.trim().isEmpty()) {
            return 0;
        }
        return userDao.countByUserType(userType);
    }

    @Override
    public long getTodayRegisteredUserCount() {
        return userDao.countTodayRegistered();
    }
    
    @Override
    public boolean isUsernameExists(String username) {
        if (username == null || username.trim().isEmpty()) {
            return false;
        }
        return userDao.existsByUsername(username.trim());
    }
    
    @Override
    public boolean isEmailExists(String email) {
        if (email == null || email.trim().isEmpty()) {
            return false;
        }
        return userDao.existsByEmail(email.trim());
    }
    
    @Override
    public boolean updateUserStatus(Integer userId, String status) {
        if (userId == null || userId <= 0 || status == null || status.trim().isEmpty()) {
            return false;
        }
        
        // 验证状态值
        if (!"active".equals(status) && !"inactive".equals(status)) {
            return false;
        }
        
        return userDao.updateStatus(userId, status) > 0;
    }
    
    @Override
    public boolean updatePassword(Integer userId, String oldPassword, String newPassword) {
        if (userId == null || userId <= 0 || 
            oldPassword == null || oldPassword.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty()) {
            return false;
        }
        
        // 验证旧密码
        User user = userDao.findById(userId);
        if (user == null || !oldPassword.equals(user.getPassword())) {
            return false;
        }
        
        // 验证新密码强度
        if (!isPasswordValid(newPassword)) {
            return false;
        }
        
        return userDao.updatePassword(userId, newPassword) > 0;
    }

    @Override
    public boolean updatePassword(Integer userId, String newPassword) {
        if (userId == null || userId <= 0 || newPassword == null || newPassword.trim().isEmpty()) {
            return false;
        }

        // 验证新密码强度
        if (!isPasswordValid(newPassword)) {
            return false;
        }

        return userDao.updatePassword(userId, newPassword) > 0;
    }

    @Override
    public boolean resetPassword(Integer userId, String newPassword) {
        if (userId == null || userId <= 0 || newPassword == null || newPassword.trim().isEmpty()) {
            return false;
        }
        
        // 验证新密码强度
        if (!isPasswordValid(newPassword)) {
            return false;
        }
        
        return userDao.updatePassword(userId, newPassword) > 0;
    }
    
    @Override
    public String validateUser(User user, boolean isUpdate) {
        if (user == null) {
            return "用户信息不能为空";
        }
        
        // 验证用户名
        if (!isUpdate && (user.getUsername() == null || user.getUsername().trim().isEmpty())) {
            return "用户名不能为空";
        }
        if (user.getUsername() != null && user.getUsername().length() > 50) {
            return "用户名长度不能超过50个字符";
        }
        
        // 验证密码
        if (!isUpdate && (user.getPassword() == null || user.getPassword().trim().isEmpty())) {
            return "密码不能为空";
        }
        if (user.getPassword() != null && !isPasswordValid(user.getPassword())) {
            return "密码长度必须在6-20个字符之间";
        }
        
        // 验证真实姓名
        if (user.getRealName() == null || user.getRealName().trim().isEmpty()) {
            return "真实姓名不能为空";
        }
        if (user.getRealName().length() > 50) {
            return "真实姓名长度不能超过50个字符";
        }
        
        // 验证电话号码
        if (user.getPhone() != null && !user.getPhone().trim().isEmpty()) {
            if (!Pattern.matches("^1[3-9]\\d{9}$", user.getPhone())) {
                return "电话号码格式不正确";
            }
        }
        
        // 验证邮箱
        if (user.getEmail() != null && !user.getEmail().trim().isEmpty()) {
            if (!Pattern.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$", user.getEmail())) {
                return "邮箱格式不正确";
            }
        }
        
        return null; // 验证通过
    }
    
    @Override
    public boolean isPasswordValid(String password) {
        return password != null && password.length() >= 6 && password.length() <= 20;
    }
}
